var House = require('../mongo/mongo').House;

module.exports = {

	create: function(house){

		return House.create(house).exec();
	},

    createMany: function(rawDocuments){

        return House.insertMany(rawDocuments).exec();
    },

	edit: function(){

	},

	getHouses: function getHouses(options){
        var query = {}, condition = {};

        if (options.text){
            query.$or = [ //多条件，数组
                {name: {$regex : options.text}}
            ]
            condition.$or = query.$or;
        }

		var start = parseInt(options.start || 0);
        var count = parseInt(options.count || 20);

        return Promise.all([
            House
                .find(query)  
                .sort({ number: -1 })
                .skip(start)
                .limit(count)
                .addCreatedAt()
                .exec(),
            House.count(condition)    
        ])
            .then(function(res){
                return res;
            })
            .catch(function(err){
                return false;
            });
    },

    getAllHouses: function getAllHouses(options){
        var query = {}, condition = {};

        if (options.text){
            query.$or = [ //多条件，数组
                {name: {$regex : options.text}}
            ]
            condition.$or = query.$or;
        }

        return Promise.all([
            House
                .find(query)  
                .sort({ number: -1 })
                .addCreatedAt()
                .exec(),
            House.count(condition)    
        ])
            .then(function(res){
                return res;
            })
            .catch(function(err){
                return false;
            });
    },

    getHouseById: function getHouseById(houseId){
        return House
                .findOne({ _id: houseId })
                .addCreatedAt()
                .exec();
    }
}



